<?php
namespace app\admin\controller;

use think\Request;
use think\Db;

class Goodsbrand extends Base
{	
	/**
	 * 品牌列表
	 * @return [type] [description]
	 */
	function index(){
		$keywords = Request()->get('keywords');
		$sort = Request()->get('brand_id')?Request()->get('brand_id'):"brand_id asc";
        $this->assign('sort',$sort);

		$query = Db::name('goods_brand')->order($sort);
		if ($keywords) {
			$query->where(" brand_name like '%{$keywords}%' ");
		}
		
		if (Request()->isAjax()) {
			$list=$query->select();
			$this->success('success','',$list);
		}else{
			$list=$query->paginate('',false,['query'=>Request()->param()]);
			return $this->fetch('index',['list'=>$list]);
		}
		
	}

	/**
	 * 添加品牌
	 * @return [type] [description]
	 */
	function add(){
		if (Request()->isPost()) {
			$data = Request()->only('brand_name,brand_desc,brand_status,brand_sort,brand_logo','post');
			!$data['brand_name'] && $this->error('品牌名不能为空');
			$data['brand_name'] = trim($data['brand_name']);

			//查看品牌是否存在
			$isset = Db::name('goods_brand')->where(['brand_name'=>$data['brand_name']])->find();
			$isset && $this->error('品牌已经存在');

			$data['brand_firstchar'] = getFirstchar($data['brand_name']);
			$re = Db::name('goods_brand')->insert($data);
			if ($re) {
				$data['brand_id']= Db::name('goods_brand')->getLastInsID();
				$this->success('新增成功','',$data);
			}else{
				$this->error('新增失败');
			}
		}else{
			return $this->fetch();
		}
	}

	/**
	 * 删除品牌
	 * @return [type] [description]
	 */
	function delete(){
		$ids = Request()->param('ids');
		if (empty($ids)) {
			$this->error('参数错误');
		}
		Db::name('goods_brand')->where(['brand_id'=>['in',$ids]])->delete();
		$this->success('删除成功');
	}

	/**
	 * 编辑品牌
	 * @return [type] [description]
	 */
	function edit(){
		if (Request()->isPost()) {
			$data = Request()->only('brand_id,brand_name,brand_desc,brand_status,brand_sort,brand_logo','post');
			if (!isset($data['brand_id']) || empty($data['brand_id'])) {
				$this->error('参数错误');
			}

			if (isset($data['brand_name'])) {
				if (empty(trim($data['brand_name']))) {
					$this->error('品牌名不能为空');
				}
				$data['brand_name'] = trim($data['brand_name']);
				//查看品牌是否存在
				$isset = Db::name('goods_brand')->where(['brand_name'=>$data['brand_name'],'brand_id'=>['neq',$data['brand_id']]])->find();
				$isset && $this->error('品牌已经存在');

				$data['brand_firstchar'] = getFirstchar($data['brand_name']);
			}

			$re = Db::name('goods_brand')->where(['brand_id'=>$data['brand_id']])->update($data);
			if ($re!==false) {
				$this->success('操作成功');
			}else{
				$this->error('操作失败');
			}
		}else{
			$brand_id=Request()->param('brand_id');
			if (empty($brand_id)) {
				$this->error('参数错误');
			}
			$info=Db::name('goods_brand')->where(['brand_id'=>$brand_id])->find();
			$this->assign('info',$info);
			return $this->fetch();
		}
	}
}